<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        form {
            width: 650px;
            margin: 50px auto;
        }

        table {
            width: 650px;
            margin: auto;
            border-collapse: collapse;
        }

        table,
        tr,
        th,
        td {
            border: 1px solid #000;
        }
    </style>
</head>

<body>
    <form>
        <input type="text" placeholder="请输入姓名" name="uname">
        <input type="text" placeholder="请输入性别" name="gender">
        <input type="text" placeholder="请输入年龄" name="age">
        <button id="btn">提交</button>
    </form>
    <table>
        <thead>
            <tr>
                <th>姓名</th>
                <th>性别</th>
                <th>年龄</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>

    <script>
        const data = localStorage.getItem('student-data')
        const arr = data ? JSON.parse(data) : []
        const tbody = document.querySelector('tbody')
        // 渲染模块
        function render() {
            const newArr = arr.map((item, i) => {
                return `
            <tr>
                <td>${item.uname}</td>
                <td>${item.gender}</td>
                <td>${item.age}</td>
                <td><a href='#' data-id=${i}>操作</a></td>
            </tr>
            `
            })
            tbody.innerHTML = newArr.join('')
        }
        render()

        // 录入模块
        const items = document.querySelectorAll('[name]')
        document.querySelector('form').addEventListener('submit', function (e) {
            e.preventDefault()
            const obj = {}
            // 非空判断
            for (let i = 0; i < items.length; i++) {
                if (items[i].value === '') {
                    return alert('请输入内容')
                }
                obj[items[i].name] = items[i].value
            }
            arr.push(obj)
            localStorage.setItem('student-data', JSON.stringify(arr))
            render()
            this.reset()
        })
        // 删除模块
        tbody.addEventListener('click', function (e) {
            if (e.target.tagName === 'A') {
                arr.splice(e.target.dataset.id, 1)
                localStorage.setItem('student-data', JSON.stringify(arr))
                render()
            }
        })

    </script>
</body>

</html>